<template>
  <div class="formTree">
    <FormBlock title="表单树" direction="column" class="left-area">
      <el-tree
        ref="tree"
        :data="treeData"
        empty-text="暂无数据"
        default-expand-all
        node-key="id"
        class="tree-box"
        icon-class="ivu-icon-ios-arrow-forward"
        highlight-current
        :draggable="true"
        :allow-drop="allowDrop"
        :render-content="renderContent"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
      >
      </el-tree>
    </FormBlock>
    <FormBlock :title="treeInfoTitle" direction="column" class="right-area">
      <div class="treeInfo">
        <Form :model="treeInfoData" :disabled="isPreview" :rules="ruleValidate" ref="form" :label-width="100">
          <Row class="code-row-bg">
            <Col span="16">
              <Form-item prop="name" :label="'指标名称'">
                <Input :disabled="isRootNode" @on-enter="save" v-model="treeInfoData.name" placeholder="请输入" />
              </Form-item>
            </Col>
          </Row>
          <Row class="code-row-bg">
            <Col span="16">
              <Form-item prop="tip" :label="'指标说明'">
                <Input type="textarea" v-model="treeInfoData.tip" @on-enter="save" placeholder="请输入" />
              </Form-item>
            </Col>
          </Row>
          <div v-if="isLeaf || isAppend">
            <Row class="code-row-bg">
              <Col span="16">
                <Form-item prop="indicator" :label="'指标值'">
                  <field-component
                    v-if="Object.keys(treeInfoData.indicator).length"
                    :attributes="treeInfoData.indicator"
                  ></field-component>
                  <Input v-else disabled placeholder="请设置指标值" />
                </Form-item>
              </Col>
              <Col span="4">
                <div class="textBtn" @click="indicatorSet()">属性设置</div>
              </Col>
            </Row>
            <Row class="code-row-bg">
              <Col span="16">
                <Form-item prop="tip" :label="'备注'">
                  <field-component
                    v-if="Object.keys(treeInfoData.notes).length && treeInfoData.notes.isShow === 1"
                    :attributes="treeInfoData.notes"
                  ></field-component>
                  <Input v-else disabled placeholder="请设置备注" />
                </Form-item>
              </Col>
              <Col span="4">
                <div class="textBtn" @click="setNotes">属性设置</div>
              </Col>
            </Row>
            <Row class="code-row-bg">
              <Col span="16">
                <Form-item prop="tip" :label="'附件'">
                  <field-component
                    v-if="Object.keys(treeInfoData.files).length && treeInfoData.files.isShow === 1"
                    :attributes="treeInfoData.files"
                  ></field-component>
                  <Input v-else disabled placeholder="请设置附件" />
                </Form-item>
              </Col>
              <Col span="4" class="textBtnBox">
                <div class="textBtn" @click="setFiles">属性设置</div>
              </Col>
            </Row>
          </div>
          <Row style="margin: 15px 0">
            <Col span="16" style="transform: translateX(35%)">
              <RPButton optType="save" style="margin-left: 80px;" @click="save" />
            </Col>
          </Row>
        </Form>
      </div>
    </FormBlock>
  </div>
</template>

<script>
import setTargetVal from './components/setTargetVal.vue'
import setNotesVal from './components/setNotesVal.vue'
import setFilesVal from './components/setFilesVal.vue'
import fieldComponent from './fieldComponent.vue'
import {
  formatIndicatorDesc,
  formatNotesDesc,
  formatFilesDesc,
  formatTooltipDesc,
  addNodeToChildren,
  updateNode
} from '../../utils/index'
import { uuid } from 'vue-uuid'
import _ from 'lodash'
export default {
  components: { fieldComponent },
  data() {
    return {
      treeInfoData: {
        name: '',
        tip: '',
        indicator: {},
        notes: {},
        files: {}
      },
      ruleValidate: {
        name: { required: true, message: '请输入指标名称', trigger: 'blur' }
      },
      isLeaf: false,
      selectedId: '', // 选中的节点ID
      isAppend: false,
      treeInfoTitle: '',
      isRootNode: false, // 根节点
      isDirty: false, // 用来标记是否修改过表单
    }
  },
  props: {
    treeData: {
      type: Array,
      default: () => []
    },
    isPreview: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    // 初始时选中第一个节点
    selectFirstNode() {
      if (!this.treeData.length) return
      this.$refs.tree.setCurrentNode(this.treeData[0])
      this.treeInfoData.name = this.treeData[0].label
      this.treeInfoData.tip = this.treeData[0].tip
      this.treeInfoTitle = this.treeData[0].label
      this.isRootNode = true
      this.isLeaf = false
    },
    onNodeSelected(node, data) {
      console.log("node", node, data)
      this.isRootNode = node.level == 1
      this.isAppend = false
      if (node.level == 1) {
        this.isLeaf = false
      } else {
        this.isLeaf = node.isLeaf
      }
      this.treeInfoData.name = data.label
      this.treeInfoData.tip = data.tip
      if (node.isLeaf && data.attributes?.length === 3) {
        data.attributes[0] && (this.treeInfoData.indicator = data.attributes[0])
        data.attributes[1] && (this.treeInfoData.notes = data.attributes[1])
        data.attributes[2] && (this.treeInfoData.files = data.attributes[2])
      } else {
        this.treeInfoData.indicator = {}
        this.treeInfoData.notes = {}
        this.treeInfoData.files = {}
      }
      this.selectedId = data.id

    },
    renderContent(h, { node, data, store }) {
      let isRootNode = node.level == 1
      return h(
        'span',
        {
          style: {
            display: 'inline-block',
            width: '100%'
          },
          class: ['tree-row', data.selected ? 'tree-row-selected' : '', data.class]
        },
        [
          h('span', [
            h(
              'span',
              {
                class: 'ivu-tree-title',
                style: {
                  fontSize: '14px'
                },
                on: {
                  click: () => {
                    this.onNodeSelected(node, data)
                  }
                },
                attrs: {
                  title: data.label
                }
              },
              data.label
            )
          ]),
          h(
            'span',
            {
              style: {
                display: 'inline-block',
                // position: "absolute",
                // right: "2px"
                width: '40px'
              }
            },
            [
              node.level < 5
                ? h(
                    'Button',
                    {
                      props: Object.assign({}, this.buttonProps),
                      style: {
                        padding: '1px 3px',
                        borderRadius: '3px'
                      },
                      on: {
                        click: () => {
                          this.append(node, data)
                        }
                      }
                    },
                    [
                      h('i', {
                        class: 'el-icon-plus',
                        style: {
                          lineHeight: 1.5
                        }
                      })
                    ]
                  )
                : '',
              h(
                'Button',
                {
                  props: Object.assign({}, this.buttonProps),
                  class: isRootNode ? 'rootNode' : '',
                  style: {
                    padding: '1px 3px 2px',
                    borderRadius: '3px'
                  },
                  on: {
                    click: () => {
                      this.remove(node, data, store)
                    }
                  }
                },
                [
                  h('i', {
                    class: 'el-icon-delete',
                    style: {
                      lineHeight: 1.5
                    }
                  })
                ]
              )
            ]
          )
        ]
      )
    },

    findAndModifyFormDesc(treeData, targetId, newFormDesc) {
      for (let item of treeData) {
        if (item.id === targetId) {
          item.formDesc = newFormDesc
          return true
        }
        if (item.children) {
          // 递归查找子节点
          if (this.findAndModifyFormDesc(item.children, targetId, newFormDesc)) {
            return true
          }
        }
      }
      return false
    },
    clearTreeInfoData() {
      this.treeInfoData.name = ''
      this.treeInfoData.tip = ''
      // 默认指标值为单行输入框
      this.treeInfoData.indicator = {
        type: 0,
        attrs: {
          maxlength: 50
        },
        control: 1
      }
      this.treeInfoData.notes = {
        // isShow: 1,
        // type: 0,
        // maxlength: 300,
        // require: 0
      }
      this.treeInfoData.files = {}
    },
    append(node, data) {
      this.clearTreeInfoData()
      this.isAppend = true
      this.isRootNode = false
      this.selectedId = data.id
      this.isLeaf = node.isLeaf
    },
    // 拖拽时判定目标节点能否被放置
    allowDrop(draggingNode, dropNode) {
      // 不能拖拽为根节点
      if (dropNode.level === 1) {
        return false
      }
      return true
    },
    removeNodeById(treeData, nodeId) {
      return treeData.filter(node => {
        if (node.id !== nodeId) {
          if (node.children) {
            node.children = this.removeNodeById(node.children, nodeId)
          }
          return true // 保留当前节点
        }
        return false // 删除当前节点
      })
    },
    remove(node, data) {
      this.$confirm({ content: '确认删除?' })
        .then(async () => {
          this.treeData = this.removeNodeById(this.treeData, data.id)
          this.$nextTick(() => {
            this.selectFirstNode()
          })
          this.$message.success({
            content: '删除成功',
            duration: 2
          })
        })
        .catch(_ => _)
    },
    save: _.debounce(async function () {
      // 新增或修改
      // 每行第一个组件得控制换行
      const valid = await this.$refs.form.validate()
      if (!valid) return
      const formDesc = []
      // 如果indicator是标题text类型，tooltip应添加到前面，否则添加到后面
      const pushIfValid = (condition, func) => {
        if (condition) {
          formDesc.push(func())
        }
      }
      pushIfValid(Object.keys(this.treeInfoData.indicator).length, () =>
        formatIndicatorDesc(this.treeInfoData.indicator, this.treeInfoData.name)
      )
      // 如果indicator是标题text类型，tooltip应添加到前面，否则添加到后面
      pushIfValid(true, () => formatTooltipDesc(this.treeInfoData.tip))
      pushIfValid(Object.keys(this.treeInfoData.notes).length && this.treeInfoData.notes.isShow === 1, () =>
        formatNotesDesc(this.treeInfoData.notes)
      )
      pushIfValid(Object.keys(this.treeInfoData.files).length && this.treeInfoData.files.isShow === 1, () =>
        formatFilesDesc(this.treeInfoData.files)
      )
      const newNode = {
        id: uuid.v1(),
        label: this.treeInfoData.name,
        tip: this.treeInfoData.tip,
        formDesc,
        attributes: [this.treeInfoData.indicator, this.treeInfoData.notes, this.treeInfoData.files]
      }
      // 根据父节点ID添加子节点
      if (this.isAppend) {
        addNodeToChildren(this.selectedId, this.isLeaf, this.treeData, newNode)
        this.$nextTick(() => {
          // this.$refs.tree.setCurrentKey(newNode.id)
          this.isAppend = false
          this.selectFirstNode()
        })
      } else {
        // 修改
        updateNode(this.selectedId, this.treeData, newNode, this.isLeaf)
      }
      // this.$Message.success({
      //   content: '保存成功',
      //   duration: 3
      // })
      this.isDirty = true
      console.log("treeData", this.treeData)
    }, 1000),
    handleNodeClick(data, node) {
      const labels = this.getAllParentLabels(node)
      this.treeInfoTitle = labels.join(' / ')
    },
    getAllParentLabels(node) {
      const labels = []
      let currentNode = node
      while (currentNode.parent) {
        labels.unshift(currentNode.data.label)
        currentNode = currentNode.parent
      }
      return labels
    },
    // 指标值设置
    indicatorSet() {
      new this.$pageModal(
        setTargetVal,
        {
          props: {
            attributes: this.treeInfoData.indicator
          }
        },
        data => {
          data && (this.treeInfoData.indicator = data)
        }
      )
    },
    // 备注设置
    setNotes() {
      new this.$pageModal(
        setNotesVal,
        {
          props: {
            attributes: this.treeInfoData.notes
          }
        },
        data => {
          data && (this.treeInfoData.notes = data)
        }
      )
    },
    // 附件设置
    setFiles() {
      new this.$pageModal(
        setFilesVal,
        {
          props: {
            attributes: this.treeInfoData.files
          }
        },
        data => {
          data && (this.treeInfoData.files = data)
        }
      )
    }
  }
}
</script>

<style lang="less">
.form-block {
  .block-body {
    width: calc(~'100% - 1px');
    .ivu-tree {
      height: calc(~'100% - 36px');
    }
  }
}
.formTree {
  display: flex;
  height: calc(100vh - 320px);
  .left-area {
    width: 40%;
    overflow-x: hidden;
    float: left;
    .tree-box {
      display: inline-block;
      width: 100%;
      .ivu-btn:focus {
        box-shadow: none;
      }
      button {
        border: 0px;
        background-color: transparent;
        font-size: 14px;
        // color: #f89c34;
        font-weight: bold;
      }
      .el-tree-node {
        button:hover {
          background-color: var(--primary-color-8);
          // color: #ff6f4b;
        }

        .tree-row {
          padding: 3px 0;
          button {
            visibility: hidden;
          }
          &:hover {
            button {
              visibility: visible;
            }
          }
        }
        .first_node {
          button {
            visibility: visible;
          }
        }
      }
      .ivu-tree-title {
        vertical-align: middle !important;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        width: calc(~'100% - 100px');
      }
      .ivu-tree-title:hover {
        background-color: #0000;
        // color: #ff6f4b;
      }
      .rootNode {
        visibility: hidden !important;
      }
    }
  }
  .right-area {
    width: 60%;
    .treeInfo {
      width: 100%;
      .textBtn {
        margin-left: 20px;
        margin-top: 6px;
        width: 120px;
        font-size: 16px;
        font-weight: 700;
        color: #f89c34;
        &:hover {
          cursor: pointer;
        }
      }
    }
  }
}
</style>
